<template>
  <div class="culture-list-page">
    <div class="page-container">
      <!-- 页面标题 -->
<!--      <div class="page-header">-->
<!--        <div class="header-content">-->
<!--          <h1>剪纸文化</h1>-->
<!--          <p>探索中华剪纸艺术的深厚底蕴，感受传统文化的独特魅力</p>-->
<!--        </div>-->
<!--      </div>-->

      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <div class="filter-content">
          <!-- 分类筛选 -->
          <div class="category-filter">
            <el-radio-group v-model="queryParams.category" @change="handleFilterChange">
              <el-radio-button :label="undefined">全部</el-radio-button>
              <el-radio-button :label="1">历史文化</el-radio-button>
              <el-radio-button :label="2">技法介绍</el-radio-button>
              <el-radio-button :label="3">作品欣赏</el-radio-button>
              <el-radio-button :label="4">文化内涵</el-radio-button>
            </el-radio-group>
          </div>

          <!-- 搜索框 -->
          <div class="search-filter">
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索文化内容..."
              @keyup.enter="handleSearchSubmit"
              @clear="handleSearchClear"
              @input="onSearchInput"
              clearable
            >
              <template #append>
                <el-button 
                  @click="handleSearchSubmit" 
                  :icon="Search" 
                  :loading="loading"
                  type="primary"
                  title="搜索"
                />
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="content-section" v-loading="loading">
        <!-- 推荐内容 -->
        <div class="recommend-section" v-if="!queryParams.keyword && !queryParams.category && recommendList.length > 0">
          <div class="section-header">
            <h2><el-icon><Star /></el-icon> 精选推荐</h2>
          </div>
          <div class="recommend-grid">
            <div
              v-for="item in recommendList"
              :key="`recommend-${item.id}`"
              class="recommend-card"
              @click="$router.push(`/culture/${item.id}`)"
            >
              <div class="card-image">
                <img :src="item.coverImage || '/default-culture.jpg'" :alt="item.title" />
                <div class="recommend-badge">推荐</div>
              </div>
              <div class="card-content">
                <h3>{{ item.title }}</h3>
                <p>{{ item.summary }}</p>
                <div class="card-stats">
                  <span><el-icon><View /></el-icon> {{ item.viewCount }}</span>
                  <span><el-icon><Star /></el-icon> {{ item.likeCount }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 文化列表 -->
        <div class="culture-list">
          <div class="list-header">
            <h2>
              <template v-if="queryParams.keyword">
                <el-icon><Search /></el-icon>
                搜索"{{ queryParams.keyword }}"
              </template>
              <template v-else-if="queryParams.category">
                {{ getCategoryText(queryParams.category) }}
              </template>
              <template v-else>
                全部文化
              </template>
            </h2>
            <div class="header-info">
              <span class="total-count">共 {{ total }} 条</span>
              <span v-if="queryParams.keyword" class="search-tip">
                <el-button 
                  size="small" 
                  @click="clearSearchKeyword" 
                  type="info" 
                  plain
                >
                  清除搜索
                </el-button>
              </span>
            </div>
          </div>

          <!-- 无数据 -->
          <div class="no-data" v-if="!loading && cultureList.length === 0">
            <el-empty description="暂无数据">
              <el-button type="primary" @click="clearFilters">清空筛选条件</el-button>
            </el-empty>
          </div>

          <!-- 数据列表 -->
          <div class="culture-grid" v-if="cultureList.length > 0">
            <div
              v-for="item in cultureList"
              :key="item.id"
              class="culture-card"
              @click="$router.push(`/culture/${item.id}`)"
            >
              <div class="card-image">
                <img :src="item.coverImage || '/default-culture.jpg'" :alt="item.title" />
                <div class="category-tag">{{ getCategoryText(item.category) }}</div>
                <div class="card-overlay">
                  <div class="overlay-buttons">
                    <el-button
                      :icon="View"
                      circle
                      @click.stop="handlePreview(item)"
                      title="查看"
                    />
                    <el-button
                      :icon="StarFilled"
                      circle
                      @click.stop="handleLike(item)"
                      title="点赞"
                    />
                    <el-button
                      :icon="Folder"
                      circle
                      @click.stop="handleFavorite(item)"
                      title="收藏"
                    />
                  </div>
                </div>
              </div>
              <div class="card-content">
                <h3>{{ item.title }}</h3>
                <p>{{ item.summary }}</p>
                <div class="card-meta">
                  <div class="card-stats">
                    <span><el-icon><View /></el-icon> {{ item.viewCount }}</span>
                    <span><el-icon><StarFilled /></el-icon> {{ item.likeCount }}</span>
                    <span><el-icon><Folder /></el-icon> {{ item.favoriteCount }}</span>
                  </div>
                  <div class="card-date">{{ formatDate(item.createTime) }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              v-model:current-page="queryParams.page"
              v-model:page-size="queryParams.size"
              :total="total"
              :page-sizes="[12, 24, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Search, Star, View, StarFilled, Folder
} from '@element-plus/icons-vue'
import { cultureApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { Culture, CultureQuery } from '@/types/common'
import { CULTURE_CATEGORIES } from '@/types/common'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const cultureList = ref<Culture[]>([])
const recommendList = ref<Culture[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<CultureQuery>({
  page: 1,
  size: 12,
  keyword: '',
  category: undefined
})

// 添加调试信息
console.log('初始化 queryParams:', queryParams)

// 获取推荐内容
const fetchRecommendList = async () => {
  try {
    const response = await cultureApi.getRecommendCultures(6)
    recommendList.value = response.data
  } catch (error) {
    console.error('获取推荐内容失败:', error)
  }
}

// 获取文化列表
const fetchCultureList = async () => {
  loading.value = true
  
  // 清理查询参数，确保传递正确的数据
  const cleanParams = {
    page: queryParams.page,
    size: queryParams.size,
    keyword: queryParams.keyword || undefined, // 空字符串转为 undefined
    category: queryParams.category
  }
  
  console.log('发送API请求，参数:', cleanParams)
  
  try {
    let response
    
    // 始终使用列表API，它支持所有查询参数（keyword、category等）
    console.log('使用列表API，参数:', cleanParams)
    response = await cultureApi.getCulturePage(cleanParams)
    
    console.log('API响应:', response.data)
    
    cultureList.value = response.data.records || []
    total.value = response.data.total || 0
    
    // 搜索结果反馈
    if (cleanParams.keyword) {
      console.log(`搜索"${cleanParams.keyword}"返回 ${total.value} 条结果`)
      if (total.value === 0) {
        ElMessage.warning(`未找到包含"${cleanParams.keyword}"的内容`)
      } else {
        ElMessage.success(`找到 ${total.value} 条相关内容`)
      }
    } else {
      console.log(`获取全部内容，共 ${total.value} 条`)
    }
    
  } catch (error) {
    ElMessage.error('获取文化列表失败')
    console.error('获取文化列表失败:', error)
    console.error('请求参数:', cleanParams)
    
    // 失败时清空列表
    cultureList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理搜索提交（点击搜索按钮或按回车）
const handleSearchSubmit = () => {
  console.log('搜索提交，原始输入:', queryParams.keyword)
  
  // 处理搜索关键词
  const keyword = queryParams.keyword ? queryParams.keyword.trim() : ''
  
  // 更新查询参数
  queryParams.keyword = keyword
  queryParams.page = 1 // 重置到第一页
  
  console.log('处理后的搜索参数:', { keyword, page: queryParams.page })
  
  if (keyword) {
    ElMessage.info(`开始搜索: ${keyword}`)
  } else {
    ElMessage.info('显示全部文化内容')
  }
  
  // 执行搜索
  performSearch()
}

// 处理搜索清空
const handleSearchClear = () => {
  console.log('搜索清空')
  queryParams.keyword = ''
  queryParams.page = 1
  ElMessage.info('已清空搜索条件')
  performSearch()
}

// 防抖定时器
let searchDebounceTimer: number | null = null

// 搜索输入变化
const onSearchInput = (value: string) => {
  console.log('搜索输入变化:', value)
  
  // 清除之前的定时器
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer)
  }
  
  // 设置防抖搜索（输入停止800ms后自动搜索）
  searchDebounceTimer = setTimeout(() => {
    const trimmedValue = value.trim()
    if (trimmedValue !== queryParams.keyword) {
      console.log('防抖搜索触发，关键词:', trimmedValue)
      queryParams.keyword = trimmedValue
      queryParams.page = 1
      
      // 防抖搜索不显示提示信息，避免干扰用户
      performSearch()
    }
  }, 800) // 800ms 防抖延迟
}

// 执行搜索
const performSearch = () => {
  console.log('执行搜索，参数:', queryParams)
  
  // 立即显示加载状态
  loading.value = true
  
  // 稍微延迟一下再调用API，让用户看到加载状态
  setTimeout(() => {
    fetchCultureList()
  }, 100)
}

// 处理筛选变化
const handleFilterChange = () => {
  console.log('筛选条件变化:', queryParams)
  queryParams.page = 1
  performSearch()
}

// 处理分页变化
const handlePageChange = () => {
  fetchCultureList()
}

// 清除搜索关键词
const clearSearchKeyword = () => {
  console.log('清除搜索关键词')
  queryParams.keyword = ''
  queryParams.page = 1
  ElMessage.info('已清除搜索关键词')
  performSearch()
}

// 清空筛选条件
const clearFilters = () => {
  queryParams.keyword = ''
  queryParams.category = undefined
  queryParams.page = 1
  ElMessage.info('已清空所有筛选条件')
  performSearch()
}

// 查看详情
const handlePreview = (item: Culture) => {
  router.push(`/culture/${item.id}`)
}

// 点赞
const handleLike = async (item: Culture) => {
  // 检查登录状态
  const userStore = useUserStore()
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    console.log('点赞操作开始 - 登录状态:', userStore.isLoggedIn, 'Token:', userStore.token)
    console.log('发送点赞请求, ID:', item.id)
    
    const response = await cultureApi.likeCulture(item.id)
    console.log('点赞响应:', response)
    
    // 解析响应数据
    const responseData = (response as any).data
    const isLiked = responseData.isLiked || responseData.liked
    const newLikeCount = responseData.likeCount
    
    // 更新本地数据
    if (typeof newLikeCount === 'number') {
      item.likeCount = newLikeCount
    } else {
      // 如果后端没有返回新的点赞数，手动更新
      if (isLiked) {
        item.likeCount++
      } else {
        item.likeCount = Math.max(0, item.likeCount - 1)
      }
    }
    
    ElMessage.success(isLiked ? '点赞成功' : '取消点赞')
  } catch (error: any) {
    console.error('点赞操作失败:', error)
    
    let errorMessage = '操作失败，请稍后重试'
    
    if (error.response?.status === 400) {
      errorMessage = '请求参数错误，请检查登录状态'
    } else if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
      userStore.logout()
      router.push('/login')
    } else if (error.message) {
      // 解析后端返回的具体错误信息
      if (error.message.includes('Duplicate entry')) {
        errorMessage = '点赞状态冲突，请刷新页面后重试'
      } else if (error.message.includes('并发冲突')) {
        errorMessage = '操作过于频繁，请稍后重试'
      } else if (error.message.includes('重试次数超限')) {
        errorMessage = '网络繁忙，请稍后重试'
      } else {
        // 使用后端返回的错误信息
        const backendMessage = error.message.replace('点赞操作失败: ', '')
        if (backendMessage && backendMessage !== error.message) {
          errorMessage = backendMessage
        }
      }
    }
    
    ElMessage.error(errorMessage)
  }
}

// 收藏
const handleFavorite = async (item: Culture) => {
  // 检查登录状态
  const userStore = useUserStore()
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    console.log('收藏操作开始, ID:', item.id)
    const response = await cultureApi.favoriteCulture(item.id)
    console.log('收藏响应:', response)
    
    // 解析响应数据
    const responseData = (response as any).data
    const isFavorited = responseData.isFavorited || responseData.favorited
    const newFavoriteCount = responseData.favoriteCount
    
    // 更新本地数据
    if (typeof newFavoriteCount === 'number') {
      item.favoriteCount = newFavoriteCount
    } else {
      // 如果后端没有返回新的收藏数，手动更新
      if (isFavorited) {
        item.favoriteCount++
      } else {
        item.favoriteCount = Math.max(0, item.favoriteCount - 1)
      }
    }
    
    ElMessage.success(isFavorited ? '收藏成功' : '取消收藏')
  } catch (error: any) {
    console.error('收藏操作失败:', error)
    if (error.response?.status === 400) {
      ElMessage.error('请求参数错误，请检查登录状态')
    } else if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      userStore.logout()
      router.push('/login')
    } else {
      ElMessage.error('操作失败，请稍后重试')
    }
  }
}

// 获取分类文本
const getCategoryText = (category: number) => {
  return CULTURE_CATEGORIES[category as keyof typeof CULTURE_CATEGORIES] || '其他'
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

onMounted(() => {
  fetchRecommendList()
  fetchCultureList()
})

onUnmounted(() => {
  // 清理防抖定时器
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer)
    searchDebounceTimer = null
  }
})
</script>

<style scoped>
.culture-list-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面标题 */
.page-header {
  background: linear-gradient(135deg, #d32f2f 0%, #f57c00 100%);
  color: #fff;
  border-radius: 12px;
  padding: 40px;
  margin-bottom: 24px;
  text-align: center;
}

.header-content h1 {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 12px;
}

.header-content p {
  font-size: 16px;
  opacity: 0.9;
}

/* 筛选区域 */
.filter-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-content {
  display: flex;
  gap: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.category-filter {
  flex: 1;
}

.search-filter {
  width: 300px;
}

/* 推荐区域 */
.recommend-section {
  margin-bottom: 32px;
}

.section-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.recommend-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.recommend-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.recommend-card .card-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.recommend-card .card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.recommend-card:hover .card-image img {
  transform: scale(1.05);
}

.recommend-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  background: linear-gradient(135deg, #d32f2f, #f57c00);
  color: #fff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

/* 列表区域 */
.culture-list {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.list-header h2 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.total-count {
  color: #666;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 40px;
}

.culture-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.culture-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.culture-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  border-color: #d32f2f;
}

.culture-card .card-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.culture-card .card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.culture-card:hover .card-image img {
  transform: scale(1.05);
}

.category-tag {
  position: absolute;
  top: 12px;
  left: 12px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none; /* 默认不捕获点击事件，让点击穿透到卡片 */
}

.culture-card:hover .card-overlay {
  opacity: 1;
  pointer-events: auto; /* hover 时允许点击 overlay 中的按钮 */
}

.overlay-buttons {
  display: flex;
  gap: 8px;
}

.overlay-buttons .el-button {
  background: rgba(255, 255, 255, 0.9);
  border: none;
  color: #333;
}

.card-content {
  padding: 16px;
}

.card-content h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content p {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.card-stats span {
  display: flex;
  align-items: center;
  gap: 2px;
}

.card-date {
  font-size: 12px;
  color: #999;
}

.pagination-container {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .page-header {
    padding: 24px 20px;
  }

  .header-content h1 {
    font-size: 24px;
  }

  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }

  .search-filter {
    width: 100%;
  }

  .recommend-grid {
    grid-template-columns: 1fr;
  }

  .culture-grid {
    grid-template-columns: 1fr;
  }
}
</style>
